import {Action,AnyAction,ReducersMapObject,Reducer} from "redux";

export function combineReducers<S,A extends Action=AnyAction>(
    reducers:ReducersMapObject<S,A>
):Reducer<S,A>
export default function combineReducers<S,A extends Action = AnyAction>(reducers:ReducersMapObject<S,A>){
    // 返回新的合并后的reducer函数
    return function (state: any = {} as S, action: A) {
        const nextState: S = {} as S;
        let key:keyof S;
        for (key in reducers) {
            const reducer:Reducer<S [typeof key],A> = reducers[key];
            const previousStateForKey:S[typeof key] = state[key];
            const nextStateForKey:S[typeof key] = reducer(previousStateForKey, action);
            nextState[key] = nextStateForKey;
        }
        return nextState;
    };
}